package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.*;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryService courseCategoryService;
    @Autowired
    private CourseTeacherService courseTeacherService;
    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private TeachplanMediaService teachplanMediaService;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //详细进行分页查询的单元测试
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        //通过课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        //根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        //通过机构id查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getCompanyId,companyId);
        //分页查询
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<CourseBase> basePage = courseBaseMapper.selectPage(page, queryWrapper);
        //查询总数
        long total = basePage.getTotal();
        List<CourseBase> items = basePage.getRecords();
        PageResult<CourseBase> pageResult = new PageResult<>(items, total, pageParams.getPageNo(), pageParams.getPageSize());
        return pageResult;
    }


    /**
     * 新增课程查询
     *
     * @param companyId
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
//        //进行合法性校验
//        if (StringUtils.isBlank(dto.getName())) {
//            throw new RuntimeException("课程名称不能为空");
//        }
//        if (StringUtils.isBlank(dto.getMt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
//        }
        //需要更新course_market以及course_base
        //创建用于返回的CourseBaseInfoDto对象
        CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto();
        //新建一个课程信息表
        CourseBase courseBaseInfoDto = new CourseBase();
        //将填写的课程信息赋值给新增对象
        BeanUtils.copyProperties(dto, courseBaseInfoDto);
        //设置审核状态
        courseBaseInfoDto.setAuditStatus("202002");
        //设置发布状态
        courseBaseInfoDto.setStatus("203001");
        //机构id
        courseBaseInfoDto.setCompanyId(companyId);
        //添加时间
        courseBaseInfoDto.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBaseInfoDto);
        if (insert <= 0) {
            throw new RuntimeException("新增课程信息表失败");
        }

        //向课程营销表中保存课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        //将填写的课程营销信息赋值给新增对象
        BeanUtils.copyProperties(dto, courseMarket);
        //将课程基本信息表中的id设置成课程营销表中的id
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(courseBaseInfoDto.getName()), CourseBase::getName, courseBaseInfoDto.getName());
        CourseBase courseBase = courseBaseMapper.selectOne(queryWrapper);
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        //插入到课程营销信息表中
        int i = saveCourseMarket(courseMarket);
        if (i <= 0) {
            throw new RuntimeException("保存营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getcourseBaseInfo(courseId);
    }


    /**
     * 插入课程营销表信息
     *
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket) {
        //收费规则
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)) {
            throw new RuntimeException("收费规则为空");
        }
        //收费规则为收费
        if (charge.equals("201001")) {
            if (courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0) {
//                throw new RuntimeException("课程为收费不能空且价格必须大于0");
                XueChengPlusException.cast("课程为收费不能空且价格必须大于0");
            }
        }
        //检查课程营销表是否存在这个课程
        CourseMarket market = courseMarketMapper.selectById(courseMarket.getId());
        if (market == null) {
            //不存在，则添加到课程营销表中
            return courseMarketMapper.insert(courseMarket);
        } else {
            //存在则进行修改
            BeanUtils.copyProperties(courseMarket, market);
            market.setId(courseMarket.getId());
            return courseMarketMapper.updateById(market);
        }

    }

    /**
     * 返回课程基本信息以及营销信息
     *
     * @param courseId
     * @return
     */
    public CourseBaseInfoDto getcourseBaseInfo(Long courseId) {
        //创建CourseBaseInfoDto对象用于返回
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //通过id查找课程信息表以及营销信息表
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket != null) {
            //将课程营销表复制给返回对象
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //查询分类名称
        String st = courseBase.getSt();
        String mt = courseBase.getMt();
        Map<String, String> map = courseCategoryService.lambdaQuery().in(CourseCategory::getId, Arrays.asList(st, mt)).list().stream()
                .collect(Collectors.toMap(CourseCategory::getId, CourseCategory::getName));
        courseBaseInfoDto.setMtName(map.get(mt));
        courseBaseInfoDto.setStName(map.get(st));
        return courseBaseInfoDto;
    }


    /**
     * 修改课程基本信息
     *
     * @param companyId
     * @param editCourseDto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //课程id
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if (!courseBase.getCompanyId().equals(companyId)) {
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        //封装基本信息的数据
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        //更新基本信息
        courseBaseMapper.updateById(courseBase);

        //封装营销信息的数据
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket!=null){
            BeanUtils.copyProperties(editCourseDto,courseMarket);
            saveCourseMarket(courseMarket);
        }

        //返回课程营销信息和基本信息
        return this.getcourseBaseInfo(courseId);

    }

    /**
     * 删除课程信息
     * @param companyid
     * @param id
     */
    @Transactional
    @Override
    public void deleteCourseBase(Long companyid, Long id) {
        //进行校验
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (!courseBase.getCompanyId().equals(companyid)){
            XueChengPlusException.cast("只允许本机构删除本机构的课程");
        }
        if (!courseBase.getAuditStatus().equals("202002")){
            XueChengPlusException.cast("只能删除课程状态为未提交的");
        }

        //删除课程基本信息以及相关联的多张表
        //1.删除课程基本信息表
        courseBaseMapper.deleteById(id);
        //2.删除课程营销表
        courseMarketMapper.deleteById(id);
        //3.删除课程计划--先删除二级节点在删除一级
        List<TeachplanDto> teachPlanTree = teachplanService.findTeachPlanTree(id);
        for (TeachplanDto teachplanDto : teachPlanTree) {
            for (TeachplanDto teachPlanTreeNode : teachplanDto.getTeachPlanTreeNodes()) {
                teachplanService.deleteTeachplan(teachPlanTreeNode.getId());
            }
            teachplanService.deleteTeachplan(teachplanDto.getId());
        }

        //4.删除课程教师信息
        List<CourseTeacher> ListTeacher = courseTeacherService.getListTeacherByCourseId(id);
        List<Long> ids = ListTeacher.stream().map(CourseTeacher::getId).collect(Collectors.toList());
        courseTeacherService.removeByIds(ids);
    }
}
